<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Initialize extends Controller_Template {

  public $template = 'templates/default';
  /**
   * @var boolean Whether the template file should be rendered automatically.
   *
   * If set, then the template view set above will be created before the controller action begins.
   * You then need to just set $this->template->content to your content, without needing to worry about the containing template.
   *
   * */
  public $auto_render = TRUE;
  /**
   * Controls access for the whole controller, if not set to FALSE we will only allow user roles specified
   *
   * Can be set to a string or an array, for example array('login', 'admin') or 'login'
   */
  public $auth_required = FALSE;
  /** Controls access for separate actions
   *
   *  Examples:
   * 'adminpanel' => 'admin' will only allow users with the role admin to access action_adminpanel
   * 'moderatorpanel' => array('login', 'moderator') will only allow users with the roles login and moderator to access action_moderatorpanel
   */
  public $secure_actions = FALSE;

  /**
   * Initialize properties before running the controller methods (actions),
   * so they are available to our action.
   */
  public function before() {
    // This codeblock is very useful in development sites:
    // What it does is get rid of invalid sessions which cause exceptions, which may happen
    // 1) when you make errors in your code.
    // 2) when the session expires!
    // Execute parent::before first
    parent::before();

    try {
      $this->session = Session::instance();
    } catch (ErrorException $e) {
      session_destroy();
    }

    // Open session
    $this->session = Session::instance();

    // Check user auth and role
    $action_name = Request::instance()->action;

    if (($this->auth_required !== FALSE && Auth::instance()->logged_in($this->auth_required) === FALSE)
            // auth is required AND user role given in auth_required is NOT logged in
            || (is_array($this->secure_actions) && array_key_exists($action_name, $this->secure_actions) && Auth::instance()->logged_in($this->secure_actions[$action_name]) === FALSE)
    // OR secure_actions is set AND the user role given in secure_actions is NOT logged in
    ) {
      if (Auth::instance()->logged_in()) {
        // user is logged in but not on the secure_actions list
        Request::instance()->redirect('user/noaccess');
      } else {
        Request::instance()->redirect('user/login');
      }
    }

    if (Auth::instance()->logged_in()) {
      $this->userAuth = Auth::instance()->get_user();
      View::set_global('messages_user_unread', ORM::factory('messages_user')->where('to_username', '=', $this->userAuth->username)->where('read', '=', null)->where('deleted_receiver', '=', null)->count_all());
      View::set_global('userAuth', Auth::instance()->get_user());
    } else {
      View::set_global('messages_user_unread', 0);
    }

    if ($this->auto_render) {
      // Initialize empty values
      $this->template->title = '';
      $this->template->meta_keywords = 'Fotografie, Fotografové, Prezentace, Práce';
      $this->template->meta_description = 'Fotografický server zaměřující se na prezentaci kvalitních fotografů, kteří se pokouší a svůj vlastní specifický pohled na svět.';
      $this->template->styles = array();
      $this->template->scripts = array();      
      $this->template->navigation = View::factory('templates/navigation');
      $this->template->navigation->active = 'index';
      $this->template->infoPanelTop = View::factory('templates/infoPanelTop');
      $this->template->footer = View::factory('templates/footer');
      $this->template->h1 = 'Photovoice';
      // ControllerName will contain the name of the Controller in the Template
      $this->template->controllerName = $this->request->controller;
      // ActionName will contain the name of the Action in the Template
      $this->template->actionName = $this->request->action;
      // next, it is expected that $this->template->content is set e.g. by rendering a view into it.
    }

    $this->system_settings = ORM::factory('system_settings')->find(1);    
    if ($this->system_settings->online == 0 && (!Auth::instance()->logged_in('admin') && $this->request->uri != 'user/login')) {
      if (Auth::instance()->logged_in()) { Auth::instance()->logout(); }
      Request::instance()->redirect('offline');
    }
    if ($this->system_settings->online == 0) {
      Message::add('warning', '<strong>Photovoice se nachází v offline módu.</strong> ');
    }
    
  }

  /**
   * Fill in default values for our properties before rendering the output.
   */
  public function after() {

    if ($this->auto_render === TRUE) {

      $cookie_theme = Cookie::get('theme');
    if (!empty($cookie_theme) && $cookie_theme !== 'default') {
        $styles = array('media/css/'.$cookie_theme.'.css' => 'screen');
        $this->template->styles = array_reverse(array_merge($styles));
      } else {
        Cookie::set('theme', 'default');
      }

      // Define defaults
      $styles = array(
          'media/js/ui/photovoice_ui.css' => 'screen',
          'media/js/ui/themes/base/jquery.ui.all.css' => 'screen',
          'media/css/default.css' => 'screen');
      $scripts = array(
          'media/js/jquery-ui-selectmenu.js',
          'media/js/jquery-ui-1.8.6.custom.min.js',
          'media/js/photovoice.js',
          'media/js/jquery.js');

      // Add defaults to template variables.
      $this->template->styles = array_reverse(array_merge($this->template->styles, $styles));
      $this->template->scripts = array_reverse(array_merge($this->template->scripts, $scripts));      

    }

    // Run anything that needs to run after this.
    parent::after();
  }

}
